﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Media.Imaging;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;

namespace Yugi.Client.Card.FileDecoder
{
    public class YFileDecoder
    {
        private YBaseCard ConvertOldVesion(YBaseCard card)
        {
            if(card.GetType() == typeof(YNormalCard))
            {
                    YMonsterCard card_new = new YMonsterCard();
                    card_new.displayImage = card.displayImage;
                    Type t1 = typeof(YNormalCard);
                    Type t2 = typeof(YMonsterCard);
                    foreach (var item in t2.GetProperties())
                    {
                        object value = t1.GetProperty(item.Name).GetValue(card, null);
                        item.SetValue(card_new, value, null);
                    }
                    card_new.Level = ((YNormalCard)card).Star;
                    return card_new;
            }
            return card;
        }

        public Yugi.Client.Card.YBaseCard BinaryFileDecoderCard(string path)
        {
            YBaseCard res = null;
            int img_length;
            MemoryStream mem_img = new MemoryStream();
            BinaryReader reader = new BinaryReader( File.OpenRead(path));
            //Read Image
            img_length = reader.ReadInt32();
            byte[] data_img = reader.ReadBytes((int)img_length);
            mem_img.Write(data_img, 0, data_img.Length);
            mem_img.Position = 0;
            JpegBitmapDecoder decoder = (JpegBitmapDecoder)JpegBitmapDecoder.Create(mem_img, BitmapCreateOptions.None, BitmapCacheOption.Default);
            //Read Data
            BinaryFormatter serial = new BinaryFormatter();
            res= serial.Deserialize(reader.BaseStream) as YBaseCard;
            res.displayImage = decoder.Frames[0];
            reader.Close();
            res=ConvertOldVesion(res);
            return res;
        }
        public Yugi.Client.Card.YBaseCard XmlFileDecoderCard(string path,string img_path)
        {
            YBaseCard res = null;
            Type[] extra={ typeof(YSpellCard) };
            XmlSerializer serial = new XmlSerializer(typeof(YBaseCard),extra);
            FileInfo f = new FileInfo(path);
            string name = f.Name;
            using (Stream str = f.Open(FileMode.Open))
            {
                res=serial.Deserialize(str) as YBaseCard;
            }

            Stream sr = new FileStream(img_path, FileMode.Open, FileAccess.Read, FileShare.Read);
            
                PngBitmapDecoder decoder = new PngBitmapDecoder(sr, BitmapCreateOptions.None,BitmapCacheOption.Default);
                res.displayImage= decoder.Frames[0];

            sr.Close();
            return res;
        }
    }
}
